import axios from 'axios';
import { store } from '../store/store';
import { updateAccessToken } from '../store/authSlice';

// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:4000', // api的base_url
    timeout: 5000 // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        // 每次请求都带上 access token
        const token = localStorage.getItem('accessToken');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        return response;
    },
    async (error) => {
        console.log('响应拦截器: ', error);
        const originalRequest = error.config;

        // 如果是 401 错误且还没重试过
        if ((error.response.status === 401 || error.response.status === 403) && !originalRequest._retry) {
            originalRequest._retry = true;

            try {
                // 调用刷新接口
                const refreshToken = localStorage.getItem('refreshToken');
                const response = await axios.post('/users/refresh', { refreshToken });

                // 更新 access token
                localStorage.setItem('accessToken', response.data.accessToken);
                if(response.data.refreshToken) {
                    localStorage.setItem('refreshToken', response.data.refreshToken);
                }
                // 同步更新redux
                store.dispatch(updateAccessToken(response.data.accessToken));
                originalRequest.headers.Authorization = `Bearer ${response.data.accessToken}`;
                return axios(originalRequest);
            } catch (refreshError) {
                // 刷新失败，跳转到登录页
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                window.location.href = '/';
                localStorage.clear();
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);

export default service;    